/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   11.05.2010
 * @version SVN: $Id: RecipeImportServiceRegistryImpl.java 130 2010-05-13 22:11:13Z christian-kerl@web.de $
 */
package org.cakis.server.service.impl;

import java.net.URL;
import java.util.*;

import org.cakis.server.Names;
import org.cakis.server.model.Recipe;
import org.cakis.server.service.RecipeImportService;
import org.cakis.server.service.RecipeImportServiceRegistry;
import org.cakis.server.service.util.NullLog;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;
import org.jboss.seam.log.Log;

/**
 * RecipeImportServiceRegistryImpl
 *
 * @author Christian Kerl
 */
@Name(Names.RecipeImportServiceRegistry)
@Scope(ScopeType.APPLICATION)
@Startup
public class RecipeImportServiceRegistryImpl implements RecipeImportServiceRegistry {

    public static abstract class SelfRegisteringRecipeImportService implements RecipeImportService {
        @In(value = Names.RecipeImportServiceRegistry, required = true, create = true)
        private RecipeImportServiceRegistry registry;

        @Create
        public void register() {
            if(registry != null) {
                registry.addService(this);
            }
        }

        @Destroy
        public void unregister() {
            if(registry != null) {
                registry.removeService(this);
            }
        }
    }

    @Logger
    private Log log = NullLog.DEFAULT;

    private final Map<String, RecipeImportService> services = new HashMap<String, RecipeImportService>();

    @Override
    public List<RecipeImportService> getServices() {
        return new ArrayList<RecipeImportService>(services.values());
    }

    @Override
    public void addService(RecipeImportService service) {
        services.put(service.getUrl().getHost(), service);

        log.info("Added RecipeImportService #0.", service.getName());
    }

    @Override
    public void removeService(RecipeImportService service) {
        services.remove(service.getUrl().getHost());

        log.info("Removed RecipeImportService #0.", service.getName());
    }

    @Override
    public Recipe getRecipeInformation(URL url) {
        log.info("Importing Recipe from #0.", url);

        Recipe result = null;

        if(services.containsKey(url.getHost())) {
            result = services.get(url.getHost()).getRecipeInformation(url);
        } else {
            log.warn("No RecipeImportService registered for Host #0.", url.getHost());
        }

        if(result != null) {
            log.info("Imported Recipe from #0.", url);
        }

        return result;
    }

}
